iT邦幫忙

1

【JavaScript】檢查Array陣列的各種方式

7514 2022-03-02 00:28:111116 瀏覽
  • 分享至 

  • xImage
  •  

本篇搭配 LeetCode 1.Two Sum

題目:

Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.

範例:

Input: nums = [2,7,11,15], target = 9
Output: [0,1]
Explanation: Because nums[0] + nums[1] == 9, we return [0, 1].

Input: nums = [3,2,4], target = 6
Output: [1,2]

Input: nums = [3,3], target = 6
Output: [0,1]

解題概念:

  1. 用 target 減去 nums[0]
  2. mapping nums 的數字有沒有 target - nums[0] 的結果
  3. 有的話就回傳結果,沒有的話再回到第1點,用 target 減去 nums[1]

indexOf() Array.indexOf('keyword')

檢查陣列裡的元素索引值。
輸出:索引值(元素的位置0/1/2...),找不到結果回傳-1

var twoSum = function(nums, target) {
    for (let i = 0 ; i < nums.length ; i++) {
        const secondNum = target - nums[i];
        if (nums.indexOf(secondNum) > -1){
            return [i , nums.indexOf(secondNum)];
        } else{
            i++
        }      
    }
};

includes() Array.includes('keyword')

檢查陣列裡是否包含元素。
輸出:布林值,找得到回傳true;找不到則回傳false

var twoSum = function(nums, target) {
    for (let i = 0 ; i < nums.length ; i++) {
        const secondNum = target - nums[i];
        if (nums.includes(secondNum)){
            return [i , nums.indexOf(secondNum)];
        } else{
            i++
        }      
    }
};

find()

使用箭頭函示檢查陣列中每個內容是否符合條件。
輸出:第一個符合條件的值;否則返回undefined

let age = [21, 43, 23, 1, 34, 12, 8];
console.log(age.find(i => i > 20));
console.log(age.find(i => i > 21))

// output
21
43 

filter()

如同 find(),使用箭頭函示檢查陣列中每個內容是否符合條件。
輸出:陣列,包含符合條件的所有值;否則返回空陣列[]

let age = [21, 43, 23, 1, 34, 12, 8];
console.log(age.filter(i => i > 20));
console.log(age.filter(i => i > 21));

// output
[21, 43, 23, 34]
[43, 23, 34]

參考來源:
https://www.delftstack.com/zh-tw/howto/javascript/javascript-array-contains/


圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言